package com.zhaogang.transactionManagerDemo.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.zhaogang.transactionManagerDemo.service.AccountTransactionService;

public class AccountTransactionServiceInvocationHandler implements InvocationHandler {
	
	private AccountTransactionService acService;	//
	
	private PlatformTransactionManager tm;
	
	
	public AccountTransactionServiceInvocationHandler() {
		super();
	}

	public AccountTransactionServiceInvocationHandler(AccountTransactionService acService,
			PlatformTransactionManager tm) {
		super();
		this.acService = acService;
		this.tm = tm;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object ret = null;
		TransactionDefinition td = new DefaultTransactionDefinition();
		TransactionStatus ts = tm.getTransaction(td);
		try {
			ret = method.invoke(acService, args);
			tm.commit(ts);
		} catch (Exception e) {
			tm.rollback(ts);
		}
		return ret;		
		
	}
	
}
